package org.jeecg.modules.bairong;

import cn.hutool.core.lang.UUID;
import com.bfd.facade.MerchantServer;
import com.bfd.util.HttpConnectionManager4;
import com.bfd.util.PropertiesUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

import static com.bfd.util.MD5Utils.genMd5;

public class bairongUtil{


//    测试apicode：3005057 （商户唯一标识）
//    测试API帐户名：chengtaiStr
//    测试API密码：chengtaiStr
    /**
     * PDF下载接口
     */
    //使用调用数据接口的账号、密码、apicode
    private static String apiCode = "3005057";
    private static String userName = "chengtaiStr";
    private static String password = "chengtaiStr";
    private static volatile String tokenid;
    private static MerchantServer ms=new MerchantServer();
    public static void main(String[] args) {
        //swift_number为请求数据接口返回的json里面的字段
//        String swift_number = "";
//        try {
//            //可以更改为自己本地存在路径
//            String filePath = "E:\\history\\"+swift_number.toString()+ UUID.randomUUID().toString()+".pdf";
//            String tokenid = getTokenid(apiCode,userName,password);
//            String result = downloadPdf(apiCode, tokenid, swift_number,filePath);
//            System.out.println("查询结果 : "+result);
//
//        }catch (Exception e){
//            e.printStackTrace();
//        }
    }

    public static String getTokenid(String LoginApi ,String apiCode,String userName,String password){
        if(StringUtils.isBlank(tokenid)){
            synchronized (bairongUtil.class) {
                if(StringUtils.isBlank(tokenid)){
                    tokenid = generateTokenid(LoginApi,apiCode,userName,password);
                }
            }
        }

        return tokenid;
    }

    private static String generateTokenid(String LoginApi ,String apiCode,String userName,String password){
        String tokenid = "";
        try {
            //登陆
            String login_res_str = ms.login(userName, password, LoginApi, apiCode);
            if(StringUtils.isNotBlank(login_res_str)){
                JSONObject loginJson=JSONObject.fromObject(login_res_str);
                if(loginJson.containsKey("tokenid")){
                    tokenid = loginJson.getString("tokenid");
                }else{
                    System.out.println("返回结果异常，无tokenid！结果为："+login_res_str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tokenid;
    }

    private static String getCheckData(String jsonData, String apiCode, String tokenId) {
        return genMd5(jsonData + genMd5(apiCode + tokenId));
    }

    private static String getUrl(String apiName) {
        return PropertiesUtil.containsKey(apiName)?PropertiesUtil.getValue(apiName).toString():apiName;
    }

    public static String downloadPdf(String apiCode, String tokenid,String swift_number, String filePath) throws Exception{
        JSONObject jsonData = new JSONObject();
        jsonData.put("swift_number", swift_number);
        String checkCode = getCheckData(jsonData.toString(), apiCode, tokenid);

        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("tokenid", tokenid);
        paramMap.put("apiCode",apiCode);
        paramMap.put("jsonData",jsonData);
        paramMap.put("checkCode",checkCode);
        System.out.println("paramMap->"+paramMap.toString());
        String url = getUrl("Pdfdownload");
        System.out.println("url====="+url);
        System.out.println("filePath====="+filePath);
      return HttpConnectionManager4.downFile(getUrl("Pdfdownload"), paramMap,filePath);

//        return HttpConnectionManager4.downFile("https://sandbox-api.100credit.cn/query_api/v1/download_approval_report", paramMap,filePath);

    }

    public static String getBrData(String tokenId, String jsonStr){
        String res="";
        try {
            res = ms.getApiData(jsonStr,apiCode);
            if(StringUtils.isNotBlank(res)){
                JSONObject json = JSONObject.fromObject(res);
                if(json.containsKey("code")&&json.getString("code").equals("100007")){
//                    tokenId = null;
                    JSONObject jsonData = JSONObject.fromObject(jsonStr);
                    jsonData.put("tokenid",tokenId);
                    res = ms.getApiData(jsonData.toString(),apiCode);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
}
